package net.joneepenk.util.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

public abstract class JdbcHelper {
	
	/**
	 * 
	 */
	protected Logger log = Logger.getLogger(this.getClass());
	
	abstract protected Connection getConnection() throws SQLException;

	protected void close(Connection conn, PreparedStatement ps, ResultSet rs) {
		try {
			if(rs != null){
				rs.close();
			}
		} catch (SQLException e) {
			log.warn("Exception is catched while close ResultSet: " + e);
		}
		try {
			if(ps != null){
				ps.close();
			}
		} catch (SQLException e) {
			log.warn("Exception is catched while close PreparedStatement: " + e);
		}
		try {
			if(conn != null && !conn.isClosed()){
				conn.close();
			}
		} catch (SQLException e) {
			log.warn("Exception is catched while close Connection: " + e);
		}
	}

	protected void setParams(Object[] params, PreparedStatement ps) throws SQLException {
		for(int i = 0; params != null && i < params.length; i++){
			JdbcParamHandler.getInstance(params[i].getClass())
					.setParam(ps, i + 1,  params[i]);
		}
	}
}
